angular.module('app').component('winitFlowMap', {
    templateUrl: getTemplateUrl('matrix/component/tpl/winitFlowMap.html'),
    bindings: {
        datas: '<',
        isReqFlow: '<',
        reqFlows: '<',
        blur: '&',
        moveFun: '&',
        addFrameFun: '&',
        addFlowFun: '&',
        editFun: '&',
        drawFun: '&',
        historyFun: '&',
        removeFun: '&',
        sortFun: '&',
        addReqFrameFun: '&',
        addReqFlowFun: '&',
        copyFlowFun: '&',
        editFlowFun: '&',
        relateFlowFun: '&',
        reliveFlowFun: '&',
        removeFlowFun: '&',
        diagramScope: '='
    },
    controller: function ($scope, $rootScope, $element, $attrs, $timeout, lodash) {
        var ctrl = this;
        console.log(ctrl);
        $scope.isReqFlow = ctrl.isReqFlow;
        $scope.datas = ctrl.datas;
        var $ = go.GraphObject.make; //监听模型数据的变化

        //  禁止右键
        if (window.Event)
            document.captureEvents(Event.MOUSEUP);

        function nocontextmenu(event) {
            event.cancelBubble = true
            event.returnValue = false;

            return false;
        }

        function norightclick(e) {
            if (window.Event) {
                if (e.which == 2 || e.which == 3)
                    return false;
            } else if (event.button == 2 || event.button == 3) {
                event.cancelBubble = true
                event.returnValue = false;
                return false;
            }
        }

        document.oncontextmenu = nocontextmenu;
        document.onmousedown = norightclick;
        // end 禁止右键

        //自适应高度
        ctrl.setTableHeight = function () {
            $timeout(function () {
                var h = document.documentElement.clientHeight || document.body.clientHeight;
                h = h - 250;
                if (document.getElementById("myDiagramFlow")) {
                    document.getElementById("myDiagramFlow").style.height = h + "px";
                }
            })
        }
        ctrl.setTableHeight();
        window.onresize = ctrl.setTableHeight;


        //添加节点右键点击菜单 start
        var cxElement = document.getElementById("contextMenu");
        var myContextMenu = $(go.HTMLInfo, {
            show: showContextMenu,
            mainElement: cxElement
        })

        function showContextMenu(obj, diagram, tool) {
            diagram.selection.each(function (node) {
                $scope.selectNode = node;
            })
            ctrl.blur({data: $scope.selectNode.data});

            //有多少个按钮就添加多少个按钮  控制该不该显示
            document.getElementById("move").style.display = canBtnShow("move") ? "block" : "none";
            document.getElementById("addFrame").style.display = canBtnShow("addFrame") ? "block" : "none";
            document.getElementById("addFlow").style.display = canBtnShow("addFlow") ? "block" : "none";
            document.getElementById("edit").style.display = canBtnShow("edit") ? "block" : "none";
            document.getElementById("draw").style.display = canBtnShow("draw") ? "block" : "none";
            document.getElementById("history").style.display = canBtnShow("history") ? "block" : "none";
            document.getElementById("removeNode").style.display = canBtnShow("removeNode") ? "block" : "none";
            document.getElementById("toSort").style.display = canBtnShow("toSort") ? "block" : "none";

            document.getElementById("addReqFrame").style.display = canBtnShow("addReqFrame") ? "block" : "none";
            document.getElementById("addReqFlow").style.display = canBtnShow("addReqFlow") ? "block" : "none";
            document.getElementById("copyFlow").style.display = canBtnShow("copyFlow") ? "block" : "none";
            document.getElementById("editFlow").style.display = canBtnShow("editFlow") ? "block" : "none";
            document.getElementById("relate").style.display = canBtnShow("relate") ? "block" : "none";
            document.getElementById("relive").style.display = canBtnShow("relive") ? "block" : "none";
            document.getElementById("remove").style.display = canBtnShow("remove") ? "block" : "none";

            cxElement.style.display = "block";
            var mousePt = diagram.lastInput.viewPoint;
            cxElement.style.left = mousePt.x + "px";
            cxElement.style.top = mousePt.y + "px";
        }

        function canBtnShow(type) {
            var data = $scope.selectNode.data;
            switch (type) {
                case "move":
                    return data.parentId != "-1" ? true : false;
                    break;
                case "addFrame":
                    return data.type == "1" ? true : false;
                    break;
                case "addFlow":
                    return data.type == "1" ? true : false;
                    break;
                case "edit":
                    return data.parentId != "-1" ? true : false;
                    break;
                case "draw":
                    return data.type == "2" ? true : false;
                    break;
                case "history":
                    return data.type == "2" ? true : false;
                    break;
                case "removeNode":
                    return data.parentId != "-1" ? true : false;
                    break;
                case "toSort":
                    return data.parentId != "-1" ? true : false;
                    break;
                case "addReqFrame":
                    return data.type == "1" ? true : false;
                    break;
                case "addReqFlow":
                    return data.type == "1" ? true : false;
                    break;
                case "copyFlow":
                    return data.type == "2" ? true : false;
                    break;
                case "editFlow":
                    return data.type == "2" ? true : false;
                    break;
                case "relate":
                    return (data.type == "2" && data.isRelate == undefined) ? true : false;
                    break;
                case "relive":
                    return (data.type == "2" && data.isRelate != undefined) ? true : false;
                    break;
                case "remove":
                    return data.type == "2" ? true : false;
                    break;
            }
        }

        // 移动
        $scope.moveBtn = function () {
            ctrl.moveFun({data: $scope.selectNode.data});
            ctrl.myDiagram.currentTool.stopTool();
        }

        // 添加框架
        $scope.addFrameBtn = function () {
            ctrl.addFrameFun({data: $scope.selectNode.data});
            ctrl.myDiagram.currentTool.stopTool();
        }

        // 添加流程
        $scope.addFlowBtn = function () {
            ctrl.addFlowFun({data: $scope.selectNode.data});
            ctrl.myDiagram.currentTool.stopTool();
        }

        // 编辑标题
        $scope.editBtn = function () {
            ctrl.editFun({data: $scope.selectNode.data});
            ctrl.myDiagram.currentTool.stopTool();
        }

        // 绘制
        $scope.drawBtn = function () {
            ctrl.drawFun({data: $scope.selectNode.data});
            ctrl.myDiagram.currentTool.stopTool();
        };

        // 历史记录
        $scope.historyBtn = function () {
            ctrl.historyFun({data: $scope.selectNode.data});
            ctrl.myDiagram.currentTool.stopTool();
        }

        // 删除
        $scope.removeBtn = function () {
            ctrl.removeFun({data: $scope.selectNode.data});
            ctrl.myDiagram.currentTool.stopTool();
        }

        // 排序
        $scope.sortBtn = function () {
            ctrl.sortFun({data: $scope.selectNode.data});
            ctrl.myDiagram.currentTool.stopTool();
        }

        // 新建req框架
        $scope.addReqFrameBtn = function() {
            ctrl.addReqFrameFun({data: $scope.selectNode.data});
            ctrl.myDiagram.currentTool.stopTool();
        }

        // 新建req流程
        $scope.addReqFlowBtn = function() {
            ctrl.addReqFlowFun({data: $scope.selectNode.data});
            ctrl.myDiagram.currentTool.stopTool();
        }

        // 复制流程
        $scope.copyFlowBtn = function() {
            ctrl.copyFlowFun({data: $scope.selectNode.data});
            ctrl.myDiagram.currentTool.stopTool();
        }

        // 编辑流程
        $scope.editFlowBtn = function() {
            ctrl.editFlowFun({data: $scope.selectNode.data});
            ctrl.myDiagram.currentTool.stopTool();
        }

        // 拉分支
        $scope.relateFlowBtn = function() {
            ctrl.relateFlowFun({data: $scope.selectNode.data});
            ctrl.myDiagram.currentTool.stopTool();
        }

        // 重置
        $scope.reliveFlowBtn = function() {
            ctrl.reliveFlowFun({data: $scope.selectNode.data});
            ctrl.myDiagram.currentTool.stopTool();
        }

        // 删除流程
        $scope.removeFlowBtn = function() {
            ctrl.removeFlowFun({data: $scope.selectNode.data});
            ctrl.myDiagram.currentTool.stopTool();
        }

        //添加节点右键点击菜单 end

        ctrl.myDiagram = $(go.Diagram, "myDiagramFlow", //页面中div的id
            {
                "toolManager.hoverDelay": 100,
                // "toolManager.mouseWheelBehavior": go.ToolManager.WheelZoom,
                isReadOnly: true,   //只读 ...为毛要只读
                allowCopy: false, //复制
                grid: $(go.Panel, "Grid", {gridCellSize: new go.Size(8, 8)},
                    $(go.Shape, "LineH", {stroke: "lightgray", strokeWidth: 0.5}),
                    $(go.Shape, "LineV", {stroke: "lightgray", strokeWidth: 0.5})
                ),
                // initialContentAlignment: go.Spot.MiddleTop, // center the content
                layout: // create a TreeLayout for the family tree
                    $(go.TreeLayout, {
                        angle: 90,
                        nodeSpacing: 5,
                        layerSpacing: 20,
                        layerStyle: go.TreeLayout.LayerUniform
                    }),
            }
        );

        //  禁止动画效果
        ctrl.myDiagram.animationManager.isEnabled = false;

        //回执图例描述
        ctrl.myDiagram.add(
            $(go.Part, "Table", {
                    position: new go.Point(-200, 10),
                    selectable: false
                },
                $(go.TextBlock, "", {
                    row: 0,
                    font: "700 14px Droid Serif, sans-serif"
                }),
                $(go.Panel, "Horizontal", {
                        row: 1,
                        alignment: go.Spot.Left
                    },
                    $(go.Shape, "Rectangle", {
                        desiredSize: new go.Size(30, 30),
                        fill: "#d4e2ef",
                        margin: 5
                    }),
                    $(go.TextBlock, "场景架构", {
                        font: "700 13px Droid Serif, sans-serif"
                    })
                ),
                $(go.Panel, "Horizontal", {
                        row: 2,
                        alignment: go.Spot.Left
                    },
                    $(go.Shape, "Rectangle", {
                        desiredSize: new go.Size(30, 30),
                        fill: "#e6f0d8",
                        margin: 5
                    }),
                    $(go.TextBlock, "场景", {font: "700 13px Droid Serif, sans-serif"})
                )
            )
        );

        //节点提示文字
        var tooltiptemplate = $(go.Adornment, "Auto",
            $(go.Shape, "Rectangle", {
                fill: "whitesmoke",
                stroke: "black"
            }),
            $(go.TextBlock, {
                    font: "bold 8pt Helvetica, bold Arial, sans-serif",
                    wrap: go.TextBlock.WrapFit,
                    margin: 5
                },
                new go.Binding("text", "name", function (name) {
                    return "名称：" + name;
                })
            )
        );

        //设置节点模板
        ctrl.myDiagram.nodeTemplate = $(go.Node, "Vertical", {
                deletable: false,
                toolTip: tooltiptemplate,
                cursor: "pointer",
                isTreeExpanded: false,
                contextMenu: myContextMenu
            },
            $(go.Panel, "Auto",
                $(go.Shape, "Rectangle", {
                        fill: "lightgray",
                        stroke: null,
                        strokeWidth: 2,
                        stretch: go.GraphObject.Fill,
                        alignment: go.Spot.Center
                    },
                    new go.Binding("stroke", "isRelate", function(isRelate) {
                        return isRelate == undefined ? null : "red";
                    }),
                    new go.Binding("fill", "type", function (type) {
                        return type == "1" ? "#d4e2ef" : "#e6f0d8";
                    })
                ),
                $(go.TextBlock, {
                        font: "700 12px Droid Serif, sans-serif",
                        textAlign: "center",
                        margin: 10,
                        maxSize: new go.Size(80, NaN),
                    },
                    new go.Binding("stroke", "isHighlighted", function (h) {
                        return h ? "red" : "black";
                    }).ofObject(),
                    new go.Binding("text", "name")
                )
            ),
            $(go.Panel, {height: 15},
                $("TreeExpanderButton")
            )
        );
        //添加节点，父节点没有展开时展开并添加
        $scope.createNode = function (childdata, status) {
            var diagram = $scope.selectNode.diagram;
            diagram.startTransaction("CollapseExpandTree");
            var data = $scope.selectNode.data;
            if (!data.everExpanded) {
                //展开父节点
                diagram.model.setDataProperty(data, "everExpanded", true);
            }
            createSubTree(data, childdata, status);
            diagram.commandHandler.expandTree($scope.selectNode);
            diagram.commitTransaction("CollapseExpandTree");
            // ctrl.myDiagram.zoomToFit();
        }

        function createSubTree(parentdata, childdata, status) {
            var model = ctrl.myDiagram.model;
            // var parent = ctrl.myDiagram.findNodeForData(parentdata);

            if(status) {
                childdata.parentId = parentdata.key;
                if(childdata.type != 1) {
                    childdata.isRelate = "red";
                }
            } else {
                childdata.parent = parentdata.key;
            }
            model.addNodeData(childdata);

        }

        $scope.updateNode = function (relateType, value) {
            if(relateType) {
                $scope.selectNode.data.isRelate = value ? "red" : null;
                if(value) {
                    ctrl.reqFlows.push($scope.selectNode.data);
                } else {
                    lodash.remove(ctrl.reqFlows, function(data) {
                        return data.id = $scope.selectNode.data.id;
                    })
                }
            }
            console.log($scope.selectNode);
            $scope.selectNode.updateTargetBindings();
        };
        $scope.moveNode = function (data) {
            var oldP = $scope.selectNode.findTreeParentNode();
            if (!oldP.data.everExpanded) {
                // 关闭旧父节点
                ctrl.myDiagram.model.setDataProperty(oldP.data, "everExpanded", false);
            }
            ctrl.myDiagram.commandHandler.collapseTree(oldP);

            var newP = ctrl.myDiagram.findNodeForKey(data.parentId);
            if (!newP.data.everExpanded) {
                //展开新父节点
                ctrl.myDiagram.model.setDataProperty(newP.data, "everExpanded", true);
            }
            ctrl.myDiagram.commandHandler.expandTree(newP);

            ctrl.myDiagram.model.removeNodeData($scope.selectNode.data);
            ctrl.myDiagram.model.addNodeData(data);

            addChild($scope.selectNode)

            // ctrl.myDiagram.zoomToFit();
        };

        function addChild(node) {
            node.findTreeChildrenNodes().each(function (child) {
                ctrl.myDiagram.model.removeNodeData(child.data);
                ctrl.myDiagram.model.addNodeData(child.data);
                if (node.findTreeChildrenNodes().count > 0) {
                    addChild(child);
                }
            })
        }

        $scope.deleteNode = function () {
            ctrl.myDiagram.model.setDataProperty($scope.selectNode.data, "everExpanded", false);
            ctrl.myDiagram.commandHandler.collapseTree($scope.selectNode);
            // ctrl.myDiagram.startTransaction("CollapseExpandTree");
            ctrl.myDiagram.model.removeNodeData($scope.selectNode.data);
            // ctrl.myDiagram.commitTransaction("CollapseExpandTree");
            // ctrl.myDiagram.zoomToFit();
        }

        $scope.getChildsData = function () {
            var parent = $scope.selectNode.findTreeParentNode();
            var list = [];
            parent.findTreeChildrenNodes().each(function (node) {
                list.push(node.data);
            })
            return list;
        }

        //设置默认展开层数
        ctrl.myDiagram.addDiagramListener("InitialLayoutCompleted", function (e) {
            e.diagram.findTreeRoots().each(function (r) {
                r.expandTree(1);
            });
        });

        //连接线模板
        ctrl.myDiagram.linkTemplate = $(go.Link, {
                routing: go.Link.Orthogonal,
                corner: 5,
                selectable: false
            },
            $(go.Shape, {
                strokeWidth: 3,
                stroke: '#424242'
            })
        );

        // 监听数据变化更新数据
        ctrl.$onChanges = function () {
            ctrl.searchInput = getStorage("searchNode");
            if (ctrl.searchInput) {
                $scope.searchNode();
            }
            ctrl.myDiagram.model = new go.TreeModel(ctrl.datas);
        }

        //节点回车查询
        $scope.myKeyup = function (e) {
            var keyCode = window.event ? e.keyCode : e.which;
            if (keyCode == 13) {
                $scope.searchNode();
            }
        };

        //查询节点
        $scope.searchNode = function () {
            var input = ctrl.searchInput;
            ctrl.myDiagram.startTransaction("highlight search");

            if (input) {
                var regex = new RegExp(input, "i");
                var results = ctrl.myDiagram.findNodesByExample({name: regex});
                ctrl.myDiagram.highlightCollection(results);

                if(results.first()) {
                    if(results.first().data) {
                        var newP = ctrl.myDiagram.findNodeForKey(results.first().data.parentId);
                        ctrl.myDiagram.model.setDataProperty(newP.data, "everExpanded", true);
                        ctrl.myDiagram.commandHandler.expandTree(newP);
                        findNodeParent(results.first().data.parentId, results.first().data.level);
                    }
                }
                if (results.count > 0) ctrl.myDiagram.centerRect(results.first().actualBounds);
            } else {
                ctrl.myDiagram.clearHighlighteds();
                closeNode(2);
            }

            setStorage("searchNode", input);
            ctrl.myDiagram.commitTransaction("highlight search");
        }

        // 根据当前节点查找父节点
        function findNodeParent(parentId, level) {
            var crtParentLevelNode = new Array();
            if(level > 2) {
                lodash.each(ctrl.datas, function(node) {
                    if(node.level == level - 1 && node.id == parentId) {
                        crtParentLevelNode.push(node);
                    }
                });
            }
            lodash.each(crtParentLevelNode, function(sltNode) {
                var newP = ctrl.myDiagram.findNodeForKey(sltNode.parentId);
                ctrl.myDiagram.model.setDataProperty(newP.data, "everExpanded", true);
                ctrl.myDiagram.commandHandler.expandTree(newP);
                findNodeParent(sltNode.parentId, sltNode.level);
            })
        }

        // 关闭打开的节点
        function closeNode(level) {
            var crtParentLevelNode = new Array();
            lodash.each(ctrl.datas, function(node) {
                if(node.level == level) {
                    crtParentLevelNode.push(node);
                }
            });
            lodash.each(crtParentLevelNode, function(sltNode) {
                var newP = ctrl.myDiagram.findNodeForKey(sltNode.parentId);
                ctrl.myDiagram.model.setDataProperty(newP.data, "everExpanded", false);
                ctrl.myDiagram.commandHandler.collapseTree(newP);
            })
        }

        //缩小事件
        $scope.zoomToFit = function () {
            ctrl.myDiagram.zoomToFit();
        };

        //居中事件
        $scope.centerRoot = function () {
            ctrl.myDiagram.scale = 1;
        };

        $scope.selectNode = null;
        //点击事件
        ctrl.myDiagram.addDiagramListener("ObjectSingleClicked", function (e) {
            $scope.selectNode = e.subject.part;
            ctrl.blur({data: e.subject.part.data});
        });

        if (ctrl.diagramScope) {
            ctrl.diagramScope = $scope;
        }
    }
});